package com.sigmatrix.h5.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sigmatrix.h5.dao.FirstLevelQrCodeDao;
import com.sigmatrix.h5.dto.ProductData;
import com.sigmatrix.h5.dto.QRCodeError;
import com.sigmatrix.h5.entity.AdminArea;
import com.sigmatrix.h5.entity.CodeCirculation;
import com.sigmatrix.h5.entity.DisDealer;
import com.sigmatrix.h5.entity.FirstLevelQRCode;
import com.sigmatrix.h5.entity.MultistageLevelQRCode;
import com.sigmatrix.h5.entity.PackStandard;
import com.sigmatrix.h5.entity.Product;
import com.sigmatrix.h5.enums.BaiduMapStatus;
import com.sigmatrix.h5.enums.InsStatus;
import com.sigmatrix.h5.enums.RegionType;
import com.sigmatrix.h5.enums.VisualCodeType;
import com.sigmatrix.h5.exception.DaoException;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.exception.ServiceException;
import com.sigmatrix.h5.service.AdminAreaService;
import com.sigmatrix.h5.service.CodeCirculationService;
import com.sigmatrix.h5.service.DisDealerService;
import com.sigmatrix.h5.service.FirstLevelQrCodeService;
import com.sigmatrix.h5.service.MultistageLevelQrCodeService;
import com.sigmatrix.h5.service.PackStandardService;
import com.sigmatrix.h5.service.ProductService;
import com.sigmatrix.h5.service.SalesAreaService;
import com.sigmatrix.h5.utils.Assert;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.QRCodeUtil;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.utils.baidu.BaiduMapUtils;
import com.sigmatrix.h5.utils.baidu.po.AddressComponent;
import com.sigmatrix.h5.utils.baidu.po.LatLngLocation;
import com.sigmatrix.h5.web.args.AnalysisParam;
import com.sigmatrix.h5.web.args.QueryQrCodeParam;
import com.sigmatrix.h5.web.mode.Analysis;
import com.sigmatrix.h5.web.mode.QrCode;
import com.sigmatrix.sc.mongo.common.service.MongoServiceImpl;
/**
 * 
 *@ClassName: FirstLevelQrCodeServiceImpl
 *@Description: 一级码表
 *@author MH
 *@date 2017年9月22日 上午9:51:38
 */
@Service
public class FirstLevelQrCodeServiceImpl extends MongoServiceImpl<FirstLevelQRCode> implements FirstLevelQrCodeService{
	
	Logger logger = LoggerFactory.getLogger(FirstLevelQrCodeServiceImpl.class);
	
	/**一级码mongo操作接口*/
	@Autowired
	private transient FirstLevelQrCodeDao firstLevelQRCodeDao;
	
	@Autowired
	MultistageLevelQrCodeService multistageLevelQrCodeService;
	
	@Autowired
	ProductService productService;
	
	@Autowired
	PackStandardService packStandardService;
	
	@Autowired
	DisDealerService distributionDealersService;
	
	@Autowired
	SalesAreaService salesAreaService;
	
	@Autowired
	AdminAreaService adminAreaService; 
	
	@Autowired
	CodeCirculationService codeCirculationService;
	
	@Override
	public QrCode findByCode(QueryQrCodeParam vo) {
		Assert.leastOneValue(vo.getQrCode(), vo.getVisualCode(), "qrCode跟visualCode不能同时为空");
		MultistageLevelQRCode multistageLevelQRCode = null;
		FirstLevelQRCode firstCode = null;
		//如果手输跟扫码都不为空，就按手输的为准
		if(StringUtils.isNotBlank(vo.getVisualCode())){
			//如果是手动输入的要判断是seqNum还是友好码
			if(CommonUtils.isNotEmpty(vo.getCodeType())){
				firstCode = findBySeqOrFriendlyCode(vo.getVisualCode(), vo.getCodeType());
				if(CommonUtils.isEmpty(firstCode)){
					multistageLevelQRCode = multistageLevelQrCodeService.findBySeqOrFriendlyCode(vo.getVisualCode(), vo.getCodeType());
				}
			}
		}else{
			//如果是扫码
			if(StringUtils.isNotBlank(vo.getQrCode())){
				//先查一级码表，如果一级码表没有就查询多级码表
				firstCode = findByQRCode(vo.getQrCode());
				if(CommonUtils.isEmpty(firstCode)){
					multistageLevelQRCode = multistageLevelQrCodeService.findByPackContent(vo.getQrCode());
				}
			}
		}
		return assembleQrCode(firstCode, multistageLevelQRCode,vo);
	}

	@Override
	public FirstLevelQRCode findByFriendlyCode(String friendlyCode) {
		FirstLevelQRCode vo = new FirstLevelQRCode();
		vo.setFriendlyCode(friendlyCode);
		vo.setEnterpriseCode(SessionUtils.getEseCode());
		return selectOne(vo);
	}

	@Override
	public FirstLevelQRCode findBySeqNum(String seqNum) {
		FirstLevelQRCode vo = new FirstLevelQRCode();
		vo.setSeqNum(seqNum);
		vo.setEnterpriseCode(SessionUtils.getEseCode());
		return selectOne(vo);
	}
	
	@Override
	public FirstLevelQRCode findBySeqNum(String seqNum, String eseCode){
		FirstLevelQRCode vo = new FirstLevelQRCode();
		vo.setSeqNum(seqNum);
		vo.setEnterpriseCode(eseCode);
		return selectOne(vo);
	}

	@Override
	public FirstLevelQRCode findByQRCode(String qrCode) {
		FirstLevelQRCode vo = new FirstLevelQRCode();
		vo.setQrCode(qrCode);
		vo.setEnterpriseCode(SessionUtils.getEseCode());
		return selectOne(vo);
	}
	
	@Override
	public FirstLevelQRCode findByQRCode(String qrCode, String eseCode){
		FirstLevelQRCode vo = new FirstLevelQRCode();
		vo.setQrCode(qrCode);
		vo.setEnterpriseCode(eseCode);
		return selectOne(vo);
	}
	
	private FirstLevelQRCode findBySeqOrFriendlyCode(String code ,Short codeType){
		if(VisualCodeType.SEQ_NUM.value.equals(codeType)){
			return findBySeqNum(code);
		}else{
			return findByFriendlyCode(code);
		}
	}
	
	/**
	 * 
	 *@Title: assembleQrCode
	 *@Description: 组装码信息
	 *@return QrCode
	 *@author MH
	 *@date 2017年10月21日 上午12:22:11
	 *@param firstCode
	 *@param mcode
	 *@param vo
	 *@return
	 */
	private QrCode assembleQrCode(FirstLevelQRCode firstCode,MultistageLevelQRCode mcode,QueryQrCodeParam vo){
		Assert.leastOneValue(firstCode, mcode, "码无效，没有查询到记录");
		//初始化QrCode
		QrCode code = initQrCode(firstCode, mcode);
		//查询一级经销商跟所在的经销商
		Assert.notNull(code.getDealerCode(), "经销商code为空");
		List<DisDealer> parents = distributionDealersService.findParents(code.getDealerCode());
		Assert.notNull(parents, "没有查询到一级经销商");
		DisDealer dealer = null;
		boolean dealerIns = false;
		for (DisDealer cursor : parents) {
			if(code.getDealerCode().equals(cursor.getCode())){
				code.setDealerName(cursor.getName());
				code.setDealerId(cursor.getId());
				code.setDealerLevel(cursor.getLevel());
			}
			if(Short.valueOf("1").equals(cursor.getLevel())){
				code.setFirstLevelDealerId(cursor.getId());
				code.setFirstLevelDealerName(cursor.getName());
				dealer = cursor;
			}
			if(cursor.getId().equals(vo.getInspectionDealerId())){
				dealerIns = true;
			}
		}
		Assert.notNull(dealer, "查询一级经销商失败，请检查经销级别是否为空");
		//从经销商的纬度判断是否是窜货
		if(CommonUtils.isNotEmpty(vo.getInspectionDealerId()) 
				&& !dealerIns){
			code.setDealerInspectionStatus(InsStatus.UNNORMAL.value);
		}else{
			code.setDealerInspectionStatus(InsStatus.NORMAL.value);
		}
		//判断地点是否窜货
		code.setScanCityName("未知");
		code.setScanProvinceName("未知");
		if(StringUtils.isNotBlank(vo.getLat()) && StringUtils.isNotBlank(vo.getLng())){
			code.setStatus(InsStatus.UNNORMAL.value);
			boolean analysis = analysisAddress(vo.getLat(), vo.getLng(), dealer,code);
			if (analysis){
				code.setAddressInspectionStatus(InsStatus.NORMAL.value);
				if(InsStatus.NORMAL.value.equals(code.getDealerInspectionStatus())){
					code.setStatus(InsStatus.NORMAL.value);
				}
			}else{
				code.setAddressInspectionStatus(InsStatus.UNNORMAL.value);
			}
		}
		return code;
	}
	/**
	 * 
	 *@Title: initQrCode
	 *@Description: 初始化一个QrCode
	 *@return QrCode
	 *@author MH
	 *@date 2017年10月21日 上午12:28:36
	 *@param firstCode
	 *@param mcode
	 *@return
	 */
	private QrCode initQrCode(FirstLevelQRCode firstCode,MultistageLevelQRCode mcode){
		QrCode code = new QrCode();
		if(CommonUtils.isNotEmpty(firstCode)){
			code.setProductId(firstCode.getProductId());
			code.setBatchCode(firstCode.getBatchCode());
			code.setOutStrageTime(firstCode.getOutStockTime());
			code.setPackLevel((short)1);
			code.setProductTime(firstCode.getProductTime());
			code.setQrCode(firstCode.getQrCode());
			code.setSeqNum(firstCode.getSeqNum());
		}else if(CommonUtils.isNotEmpty(mcode)){
			code.setProductId(mcode.getProductId());
			code.setBatchCode(mcode.getBatchCode());
			code.setOutStrageTime(mcode.getOutStockTime());
			code.setPackLevel(mcode.getPackLevel() ==null?null:mcode.getPackLevel().shortValue());
			code.setPackName(mcode.getPackName());
			code.setProductTime(mcode.getProductTime());
			code.setQrCode(mcode.getPackContent());
			code.setSeqNum(mcode.getSeqNum());
		}
		Assert.notNull(code.getProductId(), "产品id为空");
		//设置经销商编码
		CodeCirculation circulation = codeCirculationService.findByQrCode(code.getQrCode());
		Assert.notNull(circulation, "没有码流转记录，无法稽查");
		code.setDealerCode(circulation.getDealersCode());
		Assert.notNull(code.getDealerCode(), "最近一条码流转记录没有经销商信息，无法稽查");
		
		Product product = productService.findById(code.getProductId());
		Assert.notNull(product, "没有查询到产品  id:"+code.getProductId());
		code.setProductName(product.getName());
		PackStandard packStandard = packStandardService.findByProductIdAndLevel(code.getProductId(), code.getPackLevel());
		if(CommonUtils.isNotEmpty(packStandard)){
			code.setPackName(packStandard.getName());
		}
		return code;
	}
	
	/**
	 * 业务逻辑：
	 * 1.如果经销商code不为空，就按该code分析
	 * 2.如果经销商code为空，就查询下一级码的经销商
	 * 3.如果下一级码经销商code也为空就继续往下查
	 * 
	 *@Title: getDealerCode
	 *@Description: 获取经销商信息
	 *@return String
	 *@author MH
	 *@date 2017年10月26日 下午3:30:35
	 *@param mcode
	 *@return
	 */
	@Deprecated
	public String getDealerCode(MultistageLevelQRCode mcode){
		List<MultistageLevelQRCode> chirldren = multistageLevelQrCodeService.findByParent(mcode.getPackContent());
		if(CommonUtils.isNotEmpty(chirldren)){
			for (MultistageLevelQRCode cursor : chirldren) {
				if(CommonUtils.isNotEmpty(cursor.getDealersCode())){
					return cursor.getDealersCode();
				}
				return getDealerCode(cursor);
			}
		}else{
			String cs = mcode.getChilds();
			Assert.notNull(chirldren, "该码既没有经销商信息也没有下级码,无法分析是否窜货");
			String[] array = cs.split(",");
			for (int i = 0; i < array.length; i++) {
				FirstLevelQRCode firstCode = findByQRCode(array[i]);
				if(CommonUtils.isNotEmpty(firstCode) && CommonUtils.isNotEmpty(firstCode.getDealersCode())){
					return firstCode.getDealersCode();
				}
			}
			throw new MessageException("该码下级码无效,无法分析是否窜货");
		}
		return null;
	}
	
	private boolean analysisAddress(String lat,String lng,DisDealer dealer,QrCode code){
		Assert.notNull(dealer.getSalesRegion(), "一级经销商没有对应的销售区域或行政区域");
		//先根据经纬度查询地点
		LatLngLocation location = BaiduMapUtils.parseLatAndLng(lat, lng);
		Assert.notNull(location.getResult(), "无效的坐标：lat: "+lat+", lng: "+lng);
		if(!BaiduMapStatus.OK.checkValue(location.getStatus())){
			throw new MessageException(BaiduMapStatus.search(location.getStatus()).reson());
		}
		AddressComponent address = null;
		if(CommonUtils.isEmpty(address = location.getResult().getAddressComponent())
				|| StringUtils.isBlank(address.getCity()) 
				|| StringUtils.isBlank(address.getProvince())){
			code.setScanCityName("定位失败");
			code.setScanProvinceName("定位失败");
			return false;
		}
		//获取百度地图的省市
		String city = address.getCity();
		String province = address.getProvince();
		code.setScanAddress(location.getResult().getFormattedAddress());
		List<AdminArea> pcs = adminAreaService.findProvinceAndCity();
		Assert.notNull(pcs, "查询行政区划列表失败");
		pcs.stream().anyMatch(x ->{
			if(CommonUtils.isNotEmpty(code.getScanCityId()) && CommonUtils.isNotEmpty(code.getScanProvinceId())){
				return true;
			}
			if(x.getName().contains(city.replace("市", ""))){
				code.setScanCityId(x.getId());
				code.setScanCityName(x.getName());
				code.setScanProvinceId(x.getParent());
			}
			if(x.getId().equals(code.getScanProvinceId()) || x.getName().contains(province.replace("省", ""))){
				code.setScanProvinceId(x.getId());
				code.setScanProvinceName(x.getName());
			}
			return false;
		});
		//查询一级经销商的行政区域
		return saleArea2AdminArea(dealer, code).anyMatch(x -> x.getId().equals(code.getScanCityId()));
	}
	
	/**
	 * 
	 *@Title: saleArea2AdminArea
	 *@Description: 根据经销商，查询行政区域
	 *@return Stream<AdminArea>
	 *@author MH
	 *@date 2017年10月21日 上午12:08:20
	 *@param dealer
	 *@param code
	 *@return
	 */
	private Stream<AdminArea> saleArea2AdminArea(DisDealer dealer, QrCode code){
		Assert.notNull(dealer.getSalesRegion(), "销售区域为空");
		StringBuffer salesAreas = new StringBuffer();
		String[] regions = dealer.getSalesRegion().split(",");
		dealer.getRegionType();
		Stream<AdminArea> f = null;
		//如果类型为销售区域，将销售区域转化为行政区域
		if(RegionType.SALES_AREA.value.equals(dealer.getRegionType())){
			f =	Arrays.stream(regions)
				.map(x -> StringUtils.isBlank(x)?null:salesAreaService.findById(Integer.valueOf(x)))
				//获取所有销售区域对应的行政区域ID
				.flatMap(s -> (s ==null || StringUtils.isBlank(s.getZoneCodes()))?null:Arrays.stream(s.getZoneCodes().split(",")))
				//根据行政区域ID查询行政区域
				.map(x -> {
					if(StringUtils.isBlank(x)) return null;
					AdminArea area = adminAreaService.findById(Integer.valueOf(x));
					if(CommonUtils.isNotEmpty(area)){
						salesAreas.append(area.getName()).append(",");
					}
					return area;
				});
		}else{
			f =	Arrays.stream(regions)
				.map(x -> {
					if(StringUtils.isBlank(x)) return null;
					AdminArea area = adminAreaService.findById(Integer.valueOf(x));
					if(CommonUtils.isNotEmpty(area)){
						salesAreas.append(area.getName()).append(",");
					}
					return area;
				});
		}
		if(salesAreas.length() > 0)
		code.setSalesArea(salesAreas.substring(0,salesAreas.length()-1));
		return f;
	}
	@Override
	public Analysis analysis(AnalysisParam vo) {
		Analysis code = new Analysis();
		//根据经销商稽查
		code.setDealerInspectionStatus(InsStatus.NORMAL.value);
		if(CommonUtils.isNotEmpty(vo.getInspectionDealerId())){
			Assert.notNull(vo.getDealerId(), "inspectionDealerId不为空时，dealerId也不能为空");
			//查询产品对应的经销商的父级经销商
			List<DisDealer> parents = distributionDealersService.findParents(vo.getDealerId());
			Assert.notNull(parents, "没有查询到上级经销商");
			boolean dealerIns = parents.stream().anyMatch(x -> x.getId().equals(vo.getInspectionDealerId()));
			if(!dealerIns)code.setDealerInspectionStatus(InsStatus.UNNORMAL.value);
		}
		//根据地点稽查
		//查询一级经销商的销售区域或者行政区域
		DisDealer dealer = distributionDealersService.findById(vo.getFirstLevelDealerId());
		Assert.notNull(dealer, "一级经销商ID错误");
		Assert.notNull(dealer.getSalesRegion(), dealer.getRegionType(), "一级经销商没有对应的销售区域或行政区域");
		AdminArea area = adminAreaService.findById(vo.getCityId());
		Assert.notNull(area, "cityId错误");
		boolean areaIns = false;
		if(RegionType.SALES_AREA.value.equals(dealer.getRegionType())){
			//将销售区域转化为行政区域
			areaIns = Arrays.stream(dealer.getSalesRegion().split(","))
				.map(x -> salesAreaService.findById(Integer.valueOf(x)))
				.flatMap(x -> StringUtils.isBlank(x.getZoneCodes())?null:Arrays.stream(x.getZoneCodes().split(",")))
				.anyMatch(x -> analysisArea(x, area.getId()));
		}else{
			areaIns = Arrays.stream(dealer.getSalesRegion().split(","))
				.anyMatch(x -> analysisArea(x, area.getId()));
			
		}
		if(areaIns)code.setAddressInspectionStatus(InsStatus.NORMAL.value);
		else code.setAddressInspectionStatus(InsStatus.UNNORMAL.value);
		
		if(areaIns && InsStatus.NORMAL.value.equals(code.getDealerInspectionStatus()))
			code.setStatus(InsStatus.NORMAL.value);
		else
			code.setStatus(InsStatus.UNNORMAL.value);
			
		return code;
	}
	
	/**
	 * 
	 *@Title: analysisArea
	 *@Description: 分析地址是否在销售区域对应的行政区域内)
	 *@return boolean
	 *@author MH
	 *@date 2017年10月23日 下午4:31:53
	 *@param saleAreaId
	 *@param areaId
	 *@return
	 */
	private boolean analysisArea(String saleAreaId,Integer areaId){
		if(StringUtils.isBlank(saleAreaId)) return false;
		Assert.isInteger(saleAreaId, String.format("行政区域[%s]ID不是有整数", saleAreaId));
		if((areaId+"").equals(saleAreaId)) return true;
		List<AdminArea> list = adminAreaService.findByParentId(Integer.valueOf(saleAreaId));
		if(CommonUtils.isNotEmpty(list)){
			return list.stream().anyMatch(x -> areaId.equals(x.getId()));
		}
		return false;
	}
	
	/**(non-Javadoc)
	 *@Title: findFirstLevelQRCodeByQRCode
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.FirstLevelQRCodeService#findFirstLevelQRCodeByQRCode(java.lang.String, java.lang.String)
	 *@author youjun
	 *@date 2017年8月7日 下午2:29:54
	 */
	@Override
	public FirstLevelQRCode findFirstLevelQRCodeByQRCode(String enterpriseCode, String qRCode, final boolean isNeedConversion)
			throws ServiceException {
		
		try {
			final String code = QRCodeUtil.conversionQRCode(qRCode, isNeedConversion);
			return firstLevelQRCodeDao.findFirstLevelQRCodeByQRCode(enterpriseCode, code);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	
	/**
	 * (non-Javadoc)
	 *@Title: findFirstLevelQRCodeByCodeAndCodeType
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.FirstLevelQRCodeService#findFirstLevelQRCodeByCodeAndCodeType(java.lang.String, java.lang.String, boolean, int)
	 *@author youjun
	 *@date 2017年8月8日 下午3:56:23
	 */
	@Override
	public FirstLevelQRCode findFirstLevelQRCodeByCodeAndCodeType(final String enterpriseCode, final String code, final boolean isNeedConversion, 
			final int codeType) throws ServiceException {
		
		if(StringUtils.isBlank(enterpriseCode)
				||StringUtils.isBlank(code)) {
			throw new ServiceException();
		}
		final String queryCode = QRCodeUtil.conversionQRCode(code, isNeedConversion);
		FirstLevelQRCode firstLevelQRCode = null;
		try{
			if(codeType==Cons.CODE_TYPE_STANDARD || codeType==Cons.CODE_TYPE_CIPHER) {
				firstLevelQRCode = firstLevelQRCodeDao.findFirstLevelQRCodeByQRCode(enterpriseCode, queryCode);
			}else if(codeType==Cons.CODE_TYPE_FRIENDLY){
				firstLevelQRCode = firstLevelQRCodeDao.findFirstLevelQRCodeByFriendlyCode(enterpriseCode, queryCode);
			}else if(codeType==Cons.CODE_TYPE_SEQNUM){
				firstLevelQRCode = firstLevelQRCodeDao.findFirstLevelQRCodeBySeqNum(enterpriseCode, queryCode);
			}
		}catch(DaoException e){
			throw new ServiceException(e);
		}
		return firstLevelQRCode;
	}

	/**(non-Javadoc)
	 *@Title: update
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.FirstLevelQRCodeService#update(com.sigmatrix.sc.handheld.inter.entity.FirstLevelQRCode)
	 *@author youjun
	 *@date 2017年8月14日 上午11:00:25
	 */
	@Override
	public void update(final FirstLevelQRCode item) throws ServiceException {
		
		try{
			firstLevelQRCodeDao.update(item);
		}catch(DaoException e){
			throw new ServiceException(e);
		}
	}
	
	/**
	 *@Title: validateSingleLevelCode
	 *@Description: 验证单品码:非空、不包含父码、非出库/入库状态,返回错误瓶数
	 *@return void
	 *@author youjun
	 *@date 2017年8月12日 上午2:01:35
	 *@param qRCodeErrorList
	 *@param firstLevelQRCode
	 *@param operateCode 手持<b>直接</b>上传的是瓶码就传入,否则传入""
	 *@param product
	 *@param isSelf 是否为一级码本身
	 *@param type 1为出库,2为入库
	 * @throws ServiceException 
	 */
	@Override
	public int validateSingleLevelCode(final List<QRCodeError> qRCodeErrorList, final FirstLevelQRCode firstLevelQRCode,
			final String operateCode, final ProductData product, final boolean isSelf, final int type) throws ServiceException {

		if(qRCodeErrorList==null
				||product==null) {
			throw new ServiceException("参数有误");
		}
		final Integer productId = product.getProductId();
		final Map<Integer, String> packStandardMap = product.getPackStandardMap();
		final String singleUnit = product.getSingleUnit();
		StringBuilder errorMsg = null;
		QRCodeError qRCodeError = null;
		if(firstLevelQRCode==null) {
			errorMsg = new StringBuilder(singleUnit).append("码:");
			errorMsg.append(operateCode).append("不存在");
			logger.info(errorMsg.toString());
//			return new Response(Cons.RESPONSE_CODE_NO_DATA, errorMsg.toString());
			qRCodeError  = new QRCodeError(operateCode, 1, productId, errorMsg.toString());
			qRCodeErrorList.add(qRCodeError);
			return 1;
		}else{
			final String singleCode = StringUtils.isBlank(operateCode)?firstLevelQRCode.getQrCode():operateCode;
			final String parentCode = firstLevelQRCode.getParentCode();
			if(StringUtils.isNotBlank(parentCode) && isSelf) {
				errorMsg = new StringBuilder("当前").append(singleUnit).append("码存在").append(singleUnit);
				errorMsg.append(packStandardMap.get(2)).append("关联,不能进行操作");
				qRCodeError = new QRCodeError(singleCode, 1, productId, errorMsg.toString());
				qRCodeErrorList.add(qRCodeError);
				return 1; // 失败单品+1
			}
			// 暂时注释判断逻辑
			/*else if(firstLevelQRCode.getStatus()!=null){
				if(type==1&&firstLevelQRCode.getStatus()==FirstLevelQRCodeStatusEnum.OUT_STORAGE.getId().intValue()){
					qRCodeError = new QRCodeError(singleCode, 1, productId, "码已出库");
					qRCodeErrorList.add(qRCodeError);
				}else if(type==2&&firstLevelQRCode.getStatus()==FirstLevelQRCodeStatusEnum.IN_STORAGE.getId().intValue()){
					qRCodeError = new QRCodeError(singleCode, 1, productId, "码已入库");
					qRCodeErrorList.add(qRCodeError);
				}
			}*/
		}
		return 0;
	}

	/**(non-Javadoc)
	 *@Title: batchSplitOrFillParentCode
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.FirstLevelQRCodeService#batchSplitOrFillParentCode(java.lang.String, java.util.List, java.lang.String)
	 *@author youjun
	 *@date 2017年8月19日 上午11:36:24
	 */
	@Override
	public void batchSplitOrFillParentCode(final String enterpriseCode, final List<String> operateCodeList, final String parentCode) throws ServiceException {

		try{
			firstLevelQRCodeDao.batchSplitOrFillParentCode(enterpriseCode, operateCodeList, parentCode);
		}catch(DaoException e){
			throw new ServiceException(e);
		}
	}

	/**(non-Javadoc)
	 *@Title: findFirstLevelQRCodeListByCondition
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.FirstLevelQRCodeService#findFirstLevelQRCodeListByCondition(com.sigmatrix.sc.handheld.inter.entity.FirstLevelQRCode)
	 *@author youjun
	 *@date 2017年8月21日 下午1:45:02
	 */
	@Override
	public List<FirstLevelQRCode> findFirstLevelQRCodeListByCondition(FirstLevelQRCode firstLevelQRCodeCondition)
			throws ServiceException {

		try{
			return firstLevelQRCodeDao.findFirstLevelQRCodeListByCondition(firstLevelQRCodeCondition);
		}catch(DaoException e){
			throw new ServiceException(e);
		}
	}

	/**(non-Javadoc)
	 * @throws ServiceException 
	 *@Title: batchUpdateByQrCodeList
	 *@Description: 
	 *@see com.sigmatrix.sc.handheld.inter.service.FirstLevelQRCodeService#batchUpdateByQrCodeList(com.sigmatrix.sc.handheld.inter.entity.FirstLevelQRCode, java.util.List)
	 *@author youjun
	 *@date 2017年8月22日 下午3:48:20
	 */
	@Override
	public void batchUpdateByQrCodeList(FirstLevelQRCode updateFirstCode, List<String> qrCodeList) throws ServiceException {
		
		try{
			firstLevelQRCodeDao.batchUpdateByQrCodeList(updateFirstCode, qrCodeList);
		}catch(DaoException e){
			throw new ServiceException(e);
		}
	}

//	@Override
//	public List<FirstLevelQRCode> select(FirstLevelQRCode t, Map<String, String> order, String eseCode) {
//		// TODO Auto-generated method stub
//		return firstLevelQRCodeDao.se;
//	}

	
}
